package com.example.mycloudpicture.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.copier.SrcToDestCopier;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.mycloudpicture.api.aliyunai.AliYunAiApi;
import com.example.mycloudpicture.api.aliyunai.model.CreateOutPaintingTaskRequest;
import com.example.mycloudpicture.api.aliyunai.model.CreateOutPaintingTaskResponse;
import com.example.mycloudpicture.common.BaseResponse;
import com.example.mycloudpicture.common.DeleteRequest;
import com.example.mycloudpicture.common.ResultUtils;
import com.example.mycloudpicture.exception.BusinessException;
import com.example.mycloudpicture.exception.ErrorCode;
import com.example.mycloudpicture.exception.ThrowUtils;
import com.example.mycloudpicture.model.dto.file.UploadPictureResult;
import com.example.mycloudpicture.model.dto.picture.*;
import com.example.mycloudpicture.model.entity.Picture;
import com.example.mycloudpicture.model.entity.Space;
import com.example.mycloudpicture.model.entity.User;
import com.example.mycloudpicture.model.enums.PictureReviewStatusEnum;
import com.example.mycloudpicture.model.vo.PictureVo;
import com.example.mycloudpicture.model.vo.UserVo;
import com.example.mycloudpicture.service.PictureService;
import com.example.mycloudpicture.mapper.PictureMapper;
import com.example.mycloudpicture.service.SpaceService;
import com.example.mycloudpicture.utils.ColorSimilarUtils;
import com.example.mycloudpicture.utils.ColorTransformUtils;
import com.example.mycloudpicture.utils.CosManager;
import com.example.mycloudpicture.utils.FileManager;
import com.example.mycloudpicture.utils.upload.FilePictureUpload;
import com.example.mycloudpicture.utils.upload.PictureUploadTemplate;
import com.example.mycloudpicture.utils.upload.UrlPictureUpload;
import lombok.extern.slf4j.Slf4j;
import net.bytebuddy.implementation.bytecode.Throw;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.web.bind.annotation.RequestBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.awt.*;
import java.io.IOException;
import java.util.*;
import java.util.List;
import java.util.stream.Collectors;

import static com.qcloud.cos.http.HttpProtocol.https;

/**
 * @author 黄宽亮
 * @description 针对表【picture(图片)】的数据库操作Service实现
 * @createDate 2025-02-25 18:14:30
 */
@Service
@Slf4j
public class PictureServiceImpl extends ServiceImpl<PictureMapper, Picture>
        implements PictureService {

    @Resource
    private final FileManager fileManager;
    @Resource
    private UserServiceImpl userServiceImpl;
    @Resource
    private FilePictureUpload filePictureUpload;
    @Resource
    private UrlPictureUpload urlPictureUpload;
    @Resource
    private CosManager cosManager;
    @Resource
    private SpaceService spaceService;
    @Resource
    private TransactionTemplate transactionTemplate;
    @Resource
    private AliYunAiApi aliYunAiApi;

    public PictureServiceImpl(FileManager fileManager) {
        this.fileManager = fileManager;
    }

    @Override
    public void validPicture(Picture picture) {
        ThrowUtils.throwIf(picture == null, ErrorCode.PARAMS_ERROR);
        Long id = picture.getId();
        String url = picture.getUrl();
        String introduction = picture.getIntroduction();
        ThrowUtils.throwIf(ObjUtil.isEmpty(id), ErrorCode.PARAMS_ERROR, "id不能为空");
        if (StrUtil.isNotBlank(url)) {
            ThrowUtils.throwIf(url.length() > 1024, ErrorCode.PARAMS_ERROR, "url长度不能超过1024");
        }
        if (StrUtil.isNotBlank(introduction)) {
            ThrowUtils.throwIf(introduction.length() > 800, ErrorCode.PARAMS_ERROR, "简介长度不能超过800");
        }
    }

    @Override
    public PictureVo uploadPicture(Object inputSource, PictureUploadRequest pictureUploadRequest, User loginUser) {
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NO_AUTH_ERROR);
        //判断空间是否存在
        Long spaceId = pictureUploadRequest.getSpaceId();
        if(spaceId!=null){
            Space space=spaceService.getById(spaceId);
            ThrowUtils.throwIf(space==null,ErrorCode.NOT_FOUND_ERROR,"空间不存在");
            //校验空间权限
            if(!space.getUserId().equals(loginUser.getId())){
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR,"没有空间权限");
            }
            //校验额度
            if(space.getTotalCount()>=space.getMaxCount()){
                throw new BusinessException(ErrorCode.OPERATION_ERROR,"空间条数已满");
            }
            if(space.getTotalSize()>=space.getMaxSize()){
                throw  new BusinessException(ErrorCode.OPERATION_ERROR,"空间大小已满");
            }
        }
        Long pictureId = null;
        if (pictureUploadRequest != null) {
            pictureId = pictureUploadRequest.getId();
        }
        if (pictureId != null) {
            boolean exists = this.lambdaQuery()
                    .eq(Picture::getId, pictureId)
                    .exists();
            ThrowUtils.throwIf(!exists, ErrorCode.NOT_FOUND_ERROR, "图片不存在");
            Picture oldPicture = this.getById(pictureId);
            if (!oldPicture.getUserId().equals(loginUser.getId()) && !userServiceImpl.isAdmin(loginUser)) {
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
            }
            //校验空间是否一致
            //没有空间id，则复用原有图片的空间id
            if(spaceId ==null){
                if(oldPicture.getSpaceId()!=null){
                    spaceId=oldPicture.getSpaceId();
                }
            }else {
                //有空间id，则校验是否一致
                if(!oldPicture.getSpaceId().equals(spaceId)){
                    throw new BusinessException(ErrorCode.PARAMS_ERROR,"空间不一致");
                }
            }
        }
        String uploadPathPrefix ;
        if(spaceId==null){
            //按照用户id划分目录
            uploadPathPrefix = String.format("public/%s", loginUser.getId());
        }else {
            //按照空间id划分目录
            uploadPathPrefix = String.format("space/%s", spaceId);
        }

        //根据inputSource区分上传的方式
        PictureUploadTemplate pictureUploadTemplate = null;
        if (inputSource instanceof String) {
            pictureUploadTemplate = urlPictureUpload;
        } else {
            pictureUploadTemplate = filePictureUpload;
        }
        UploadPictureResult uploadPictureResult = pictureUploadTemplate.uploadPicture(inputSource, uploadPathPrefix);
        Picture picture = new Picture();
        picture.setUrl(uploadPictureResult.getUrl());
        String picName = uploadPictureResult.getPicName();
        if (pictureUploadRequest != null && StrUtil.isNotBlank(pictureUploadRequest.getPicName())) {
            picName = pictureUploadRequest.getPicName();
        }
        picture.setName(picName);
        picture.setPicSize(uploadPictureResult.getPicSize());
        picture.setPicWidth(uploadPictureResult.getPicWidth());
        picture.setPicHeight(uploadPictureResult.getPicHeight());
        picture.setPicFormat(uploadPictureResult.getPicFormat());
        picture.setPicScale(uploadPictureResult.getPicScale());
        picture.setUserId(loginUser.getId());
        picture.setSpaceId(spaceId);
        // 转换为标准颜色
        picture.setPicColor(ColorTransformUtils.getStandardColor(uploadPictureResult.getPicColor()));
        this.fillReviewParams(picture, loginUser);
        if (pictureId != null) {
            picture.setId(pictureId);
            picture.setEditTime(new Date());
        }

        Long finalSpaceId = spaceId;
        transactionTemplate.execute(status -> {
            // 插入数据
            boolean result = this.saveOrUpdate(picture);
            ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "图片上传失败，数据库操作失败");
            if (finalSpaceId != null) {
                //更新空间的使用额度
                spaceService.lambdaUpdate()
                        .eq(Space::getId, finalSpaceId)
                        .setSql("totalCount = totalCount + 1,totalSize = totalSize + " + picture.getPicSize())
                        .update();
            }
            return picture;
        });
        return PictureVo.objToVo(picture);
    }

    @Override
    public PictureVo getPictureVO(Picture picture, HttpServletRequest request) {
        PictureVo pictureVo = PictureVo.objToVo(picture);
        Long userId = pictureVo.getUserId();
        if (userId != null && userId > 0) {
            User user = userServiceImpl.getById(userId);
            UserVo userVo = userServiceImpl.getUserVo(user);
            pictureVo.setUser(userVo);
        }
        return pictureVo;
    }

    @Override
    public Page<PictureVo> getPictureVOPage(Page<Picture> picturePage, HttpServletRequest request) {
        List<Picture> pictures = picturePage.getRecords();
        Page<PictureVo> pictureVoPage = new Page<>(picturePage.getCurrent(), picturePage.getSize(), picturePage.getTotal());
        if (CollUtil.isEmpty(pictures)) {
            return pictureVoPage;
        }
        List<PictureVo> pictureVoList = pictures.stream().map(PictureVo::objToVo).collect(Collectors.toList());
        Set<Long> userIdSet = pictures.stream().map(Picture::getUserId).collect(Collectors.toSet());
        Map<Long, List<User>> userIdUserListMap = userServiceImpl.listByIds(userIdSet).stream().collect(Collectors.groupingBy(User::getId));
        pictureVoList.forEach(pictureVo -> {
            Long userId = pictureVo.getUserId();
            User user = null;
            if (userIdUserListMap.containsKey(userId)) {
                user = userIdUserListMap.get(userId).get(0);
            }
            pictureVo.setUser(userServiceImpl.getUserVo(user));
        });
        pictureVoPage.setRecords(pictureVoList);
        return pictureVoPage;
    }

    @Override
    public QueryWrapper<Picture> getQueryWrapper(PictureQueryRequest pictureQueryRequest) {
        QueryWrapper<Picture> queryWrapper = new QueryWrapper<>();
        if (pictureQueryRequest == null) {
            return queryWrapper;
        }
        Long id = pictureQueryRequest.getId();
        String name = pictureQueryRequest.getName();
        String introduction = pictureQueryRequest.getIntroduction();
        String category = pictureQueryRequest.getCategory();
        List<String> tags = pictureQueryRequest.getTags();
        Long picSize = pictureQueryRequest.getPicSize();
        Integer picWidth = pictureQueryRequest.getPicWidth();
        Integer picHeight = pictureQueryRequest.getPicHeight();
        Double picScale = pictureQueryRequest.getPicScale();
        String picFormat = pictureQueryRequest.getPicFormat();
        String searchText = pictureQueryRequest.getSearchText();
        Long userId = pictureQueryRequest.getUserId();
        Integer reviewStatus = pictureQueryRequest.getReviewStatus();
        String reviewMessage = pictureQueryRequest.getReviewMessage();
        Long reviewerId = pictureQueryRequest.getReviewerId();
        Long spaceId = pictureQueryRequest.getSpaceId();
        Date startEditTime = pictureQueryRequest.getStartEditTime();
        Date endEditTime = pictureQueryRequest.getEndEditTime();
        boolean nullSpaceId = pictureQueryRequest.isNullSpaceId();
        String sortField = pictureQueryRequest.getSortField();
        String sortOrder = pictureQueryRequest.getSortOrder();

        // 从多字段中搜索
        if (StrUtil.isNotBlank(searchText)) {
            // 需要拼接查询条件
            // and (name like "%xxx%" or introduction like "%xxx%")
            queryWrapper.and(
                    qw -> qw.like("name", searchText)
                            .or()
                            .like("introduction", searchText)
            );
        }
        queryWrapper.eq(ObjUtil.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjUtil.isNotEmpty(userId), "userId", userId);
        queryWrapper.eq(ObjUtil.isNotEmpty(spaceId), "spaceId", spaceId);
        queryWrapper.isNull(nullSpaceId, "spaceId");
        queryWrapper.like(StrUtil.isNotBlank(name), "name", name);
        queryWrapper.like(StrUtil.isNotBlank(introduction), "introduction", introduction);
        queryWrapper.like(StrUtil.isNotBlank(picFormat), "picFormat", picFormat);
        queryWrapper.like(StrUtil.isNotBlank(reviewMessage), "reviewMessage", reviewMessage);
        queryWrapper.eq(StrUtil.isNotBlank(category), "category", category);
        queryWrapper.eq(ObjUtil.isNotEmpty(picWidth), "picWidth", picWidth);
        queryWrapper.eq(ObjUtil.isNotEmpty(picHeight), "picHeight", picHeight);
        queryWrapper.eq(ObjUtil.isNotEmpty(picSize), "picSize", picSize);
        queryWrapper.eq(ObjUtil.isNotEmpty(picScale), "picScale", picScale);
        queryWrapper.eq(ObjUtil.isNotEmpty(reviewStatus), "reviewStatus", reviewStatus);
        queryWrapper.eq(ObjUtil.isNotEmpty(reviewerId), "reviewerId", reviewerId);
        // >= startEditTime
        queryWrapper.ge(ObjUtil.isNotEmpty(startEditTime), "editTime", startEditTime);
        // < endEditTime
        queryWrapper.lt(ObjUtil.isNotEmpty(endEditTime), "editTime", endEditTime);
        // JSON 数组查询
        if (CollUtil.isNotEmpty(tags)) {
            /* and (tag like "%\"Java\"%" and like "%\"Python\"%") */
            for (String tag : tags) {
                queryWrapper.like("tags", "\"" + tag + "\"");
            }
        }
        // 排序
        queryWrapper.orderBy(StrUtil.isNotEmpty(sortField), sortOrder.equals("ascend"), sortField);
        return queryWrapper;
    }

    @Override
    public void doPictureReview(PictureReviewRequest pictureReviewRequest, User loginUser) {
        ThrowUtils.throwIf(pictureReviewRequest == null || loginUser == null, new BusinessException(ErrorCode.PARAMS_ERROR));
        Long id = pictureReviewRequest.getId();
        String reviewMessage = pictureReviewRequest.getReviewMessage();
        Integer reviewStatus = pictureReviewRequest.getReviewStatus();
        PictureReviewStatusEnum reviewStatusEnum = PictureReviewStatusEnum.getEnumByValue(reviewStatus);
        if (id == null || reviewStatusEnum == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Picture oldPicture = this.getById(id);
        ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR);
        if (oldPicture.getReviewStatus().equals(reviewStatus)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请勿重复审核");
        }
        Picture updatePicture = new Picture();
        BeanUtils.copyProperties(pictureReviewRequest, updatePicture);
        updatePicture.setReviewStatus(reviewStatus);
        updatePicture.setReviewTime(new Date());
        boolean result = this.updateById(updatePicture);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
    }

    public void fillReviewParams(Picture picture, User loginUser) {
        if (userServiceImpl.isAdmin(loginUser)) {
            picture.setReviewStatus(PictureReviewStatusEnum.REVIEW_PASSED.getValue());
            picture.setReviewerId(loginUser.getId());
            picture.setReviewMessage("管理自动过审");
            picture.setReviewTime(new Date());
        } else {
            picture.setReviewStatus(PictureReviewStatusEnum.PENDING_REVIEW.getValue());
        }
    }

    @Override
    public int uploadPictureByBatch(PictureUploadByBatchRequest pictureUploadByBatchRequest, User loginUser) {
        String searchText = pictureUploadByBatchRequest.getSearchText();
        // 格式化数量
        Integer count = pictureUploadByBatchRequest.getCount();
        ThrowUtils.throwIf(count > 30, ErrorCode.PARAMS_ERROR, "最多 30 条");
        // 要抓取的地址
        String fetchUrl = String.format("https://cn.bing.com/images/async?q=%s&mmasync=1", searchText);
        Document document;
        try {
            document = Jsoup.connect(fetchUrl).get();
        } catch (IOException e) {
            log.error("获取页面失败", e);
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "获取页面失败");
        }
        Element div = document.getElementsByClass("dgControl").first();
        if (ObjUtil.isNull(div)) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "获取元素失败");
        }
        Elements imgElementList = div.select("img.mimg");
        int uploadCount = 0;
        for (Element imgElement : imgElementList) {
            String fileUrl = imgElement.attr("src");
            if (StrUtil.isBlank(fileUrl)) {
                log.info("当前链接为空，已跳过: {}", fileUrl);
                continue;
            }
            // 处理图片上传地址，防止出现转义问题
            int questionMarkIndex = fileUrl.indexOf("?");
            if (questionMarkIndex > -1) {
                fileUrl = fileUrl.substring(0, questionMarkIndex);
            }
            // 上传图片
            String namePrefix = pictureUploadByBatchRequest.getNamePrefix();
            if (StrUtil.isBlank(namePrefix)) {
                namePrefix = searchText;
            }
            PictureUploadRequest pictureUploadRequest = new PictureUploadRequest();
            pictureUploadRequest.setPicName(namePrefix+(uploadCount+1));
            pictureUploadRequest.setFileUrl(fileUrl);
            try {
                PictureVo pictureVO = this.uploadPicture(fileUrl, pictureUploadRequest, loginUser);
                log.info("图片上传成功, id = {}", pictureVO.getId());
                uploadCount++;
            } catch (Exception e) {
                log.error("图片上传失败", e);
                continue;
            }
            if (uploadCount >= count) {
                break;
            }
        }
        return uploadCount;
    }

    @Async //使用默认线程池
    @Override
    public void clearPicture(Picture oldPicture) {
        String pictureUrl = oldPicture.getUrl();
        long count=this.lambdaQuery()
                .eq(Picture::getUrl,pictureUrl)
                .count();
        //如果不止一条记录用到了该图片，不清理
        if(count>1){
            return;
        }
        cosManager.deleteObject(pictureUrl);
        //删除缩略图
        String thumbnailUrl = oldPicture.getThumbnailUrl();
        if(StrUtil.isNotBlank(thumbnailUrl)){
            cosManager.deleteObject(thumbnailUrl);
        }
    }

    @Override
    public void checkPictureAuth(User loginUser, Picture picture) {
        Long spaceId=picture.getSpaceId();
        Long loginUserId=loginUser.getId();
        if(spaceId==null){
            if(!picture.getUserId().equals(loginUserId)&&!userServiceImpl.isAdmin(loginUser)){
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
            }
        }else {
            if(!picture.getUserId().equals(loginUserId)){
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
            }
        }
    }

    @Override
    public void editPicture(PictureEditRequest pictureEditRequest, User loginUser) {
        Picture picture=new Picture();
        BeanUtil.copyProperties(pictureEditRequest,picture);
        picture.setTags(JSONUtil.toJsonStr(pictureEditRequest.getTags()));
        //设置编辑时间
        picture.setEditTime(new Date());
        //数据校验
        this.validPicture(picture);
        //判断是否存在
        long id=pictureEditRequest.getId();
        Picture oldPicture=this.getById(id);
        ThrowUtils.throwIf(oldPicture==null,ErrorCode.NOT_FOUND_ERROR);
        //校验权限
        checkPictureAuth(loginUser,oldPicture);
        //补充审核参数
        this.fillReviewParams(picture,loginUser);
        //更新数据库
        boolean result=this.updateById(picture);
        ThrowUtils.throwIf(!result,ErrorCode.OPERATION_ERROR);
    }

    @Override
    public List<PictureVo> searchPictureByColor(Long spaceId, String picColor, User loginUser) {
        //校验参数
        ThrowUtils.throwIf(spaceId==null||StrUtil.isBlank(picColor),ErrorCode.PARAMS_ERROR);
        ThrowUtils.throwIf(loginUser==null,ErrorCode.NO_AUTH_ERROR);
        //校验空间权限
        Space space =spaceService.getById(spaceId);
        ThrowUtils.throwIf(space==null,ErrorCode.NOT_FOUND_ERROR,"空间不存在");
        if(!space.getUserId().equals(loginUser.getId())){
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR,"没有空间访问权限");
        }
        //查询该空间下所有的图片
        List<Picture> pictureList=this.lambdaQuery()
                .eq(Picture::getSpaceId,spaceId)
                .isNotNull(Picture::getPicColor)
                .list();
        //如果没有图片，直接返回空列表
        if(CollUtil.isEmpty(pictureList)){
            return new ArrayList<>();
        }
        Color targetColor=Color.decode(picColor);
        List<Picture> pictureVoList=pictureList.stream().sorted(Comparator.comparingDouble(p -> {
            String hexColor = p.getPicColor();
            if(StrUtil.isBlank(hexColor)){
                return Double.MAX_VALUE;
            }
            Color pictureColor = Color.decode(picColor);
            return -ColorSimilarUtils.calculateSimilarity(pictureColor,targetColor);
        })).limit(12).collect(Collectors.toList());
        return pictureVoList.stream().map(PictureVo::objToVo).collect(Collectors.toList());
    }

    @Override
    public void editPictureByBatch(PictureEditByBatchRequest pictureEditByBatchRequest, User loginUser) {
        //1.获取校验参数
        List<Long> pictureIdList = pictureEditByBatchRequest.getPictureIdList();
        Long spaceId=pictureEditByBatchRequest.getSpaceId();
        String category=pictureEditByBatchRequest.getCategory();
        List<String> tags=pictureEditByBatchRequest.getTags();
        ThrowUtils.throwIf(CollUtil.isEmpty(pictureIdList),ErrorCode.PARAMS_ERROR);
        ThrowUtils.throwIf(spaceId==null,ErrorCode.PARAMS_ERROR);
        ThrowUtils.throwIf(loginUser==null,ErrorCode.NO_AUTH_ERROR);
        //2.校验空间权限
        Space space =spaceService.getById(spaceId);
        ThrowUtils.throwIf(space==null,ErrorCode.NOT_FOUND_ERROR,"空间不存在");
        if(!space.getUserId().equals(loginUser.getId())){
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR,"没有空间访问权限");
        }
        //3.查询指定图片（仅选择需要的字段）
        List<Picture> pictureList=this.lambdaQuery()
                .select(Picture::getId,Picture::getPicSize,Picture::getSpaceId)
                .eq(Picture::getSpaceId,spaceId)
                .in(Picture::getId,pictureIdList)
                .list();
        if(pictureList.isEmpty()){
            return;
        }
        //4.更新分类和标签
        pictureList.forEach(picture -> {
            if(StrUtil.isNotBlank(category)){
                picture.setCategory(category);
            }
            if(CollUtil.isNotEmpty(tags)){
                picture.setTags(JSONUtil.toJsonStr(tags));
            }
        });
        //批量重命名
        String nameRule= pictureEditByBatchRequest.getNameRule();
        this.fillPictureWithNameRule(pictureList,nameRule);
        //5.操作数据库进行批量更新
        boolean result = this.updateBatchById(pictureList);
        ThrowUtils.throwIf(!result,ErrorCode.OPERATION_ERROR,"批量更新失败");
    }

    @Override
    public void fillPictureWithNameRule(List<Picture> pictureList,String nameRule){
        if(StrUtil.isBlank(nameRule)||CollUtil.isEmpty(pictureList)){
            return;
        }
        long count=1;
        try {
            for(Picture picture:pictureList){
                String pictureName= nameRule.replaceAll("\\{序号}",String.valueOf(count++));
                picture.setName(pictureName);
            }
        } catch (Exception e) {
            log.error("名称解析错误",e);
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"名称解析错误");
        }
    }

    @Override
    public CreateOutPaintingTaskResponse createPictureOutPaintingTask(CreatePictureOutPaintingTaskRequest createPictureOutPaintingTaskRequest, User loginUser) {
        //获取图片信息
        Long pictureId = createPictureOutPaintingTaskRequest.getPictureId();
        Picture picture = Optional.of(this.getById(pictureId)).orElseThrow(() -> new BusinessException(ErrorCode.NOT_FOUND_ERROR,"图片不存在"));
        //校验权限
        checkPictureAuth(loginUser,picture);
        //创建扩图任务
        CreateOutPaintingTaskRequest createOutPaintingTaskRequest = new CreateOutPaintingTaskRequest();
        CreateOutPaintingTaskRequest.Input input=new CreateOutPaintingTaskRequest.Input();
        input.setImageUrl(picture.getUrl());
        createOutPaintingTaskRequest.setInput(input);
        createOutPaintingTaskRequest.setParameters(createPictureOutPaintingTaskRequest.getParameters());
        return aliYunAiApi.createOutPaintingTask(createOutPaintingTaskRequest);
    }

    @Override
    public void deletePicture(long pictureId, User loginUser) {
        ThrowUtils.throwIf(pictureId<=0,ErrorCode.PARAMS_ERROR);
        ThrowUtils.throwIf(loginUser==null,ErrorCode.NO_AUTH_ERROR);
       Picture oldPicture=this.getById(pictureId);
       ThrowUtils.throwIf(oldPicture==null,ErrorCode.NOT_FOUND_ERROR);
       //校验权限
        checkPictureAuth(loginUser,oldPicture);
        //开启事务
        transactionTemplate.execute(status -> {
            //操作数据库
            boolean result=this.removeById(pictureId);
            ThrowUtils.throwIf(!result,ErrorCode.OPERATION_ERROR);
            //更新空间的使用额度，释放额度
            boolean update=spaceService.lambdaUpdate()
                    .eq(Space::getId,oldPicture.getSpaceId())
                    .setSql("totalSize=totalSize-"+oldPicture.getPicSize())
                    .setSql("totalCount=totalCount-1")
                    .update();

            ThrowUtils.throwIf(!update,ErrorCode.OPERATION_ERROR,"更新空间使用额度失败");
            return true;
        });
        //异步清理文件
        this.clearPicture(oldPicture);
    }
}




